package com.eeepay.eeepay_v2.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.util.BaseGrpcTask;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.view.CustomChooseView;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.eeepay.api.grpc.nano.PosNameApiServiceGrpc;
import cn.eeepay.api.grpc.nano.PosNameProto;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/1 0001.
 * 硬件类型   狗日的非要换成这个
 */
public class PosTypeActivity extends ABBaseActivity implements View.OnClickListener {

    private final int DEVICE_TYPE = 0;
    private final int PROBLEM_TYPE = 1;
    private TitleBar titleBar;
    private LinearLayout layout_content;
    private RelativeLayout rl_all;
    private ImageView iv_all;

    private boolean isSingle = true;// 是否是单选
    private boolean isAll = false;//是否全选
    private PosNameProto.HardProductMsg[] posMsgs;
    private StringBuffer posIdStr = new StringBuffer("");

    private Intent intent;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_type;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.title_bar);
//        titleBar.setShowRight(View.VISIBLE);
        //add by zhuangzeqin 隐藏右边按钮
        titleBar.setShowRight(View.GONE);
        titleBar.setRightTextView("确定");
        titleBar.setRightTextColor(R.color.unify_grounding_white);

        layout_content = getViewById(R.id.layout_content);
        rl_all = getViewById(R.id.layout_all);
        iv_all = getViewById(R.id.iv_all);

//        if(bundle != null){
//            isSingle = bundle.getBoolean("isSingle");
//        }
        if(isSingle){
            rl_all.setVisibility(View.GONE);
        }

        sendHttpRequest(DEVICE_TYPE);



    }

    private void initData(){
        List<PosNameProto.HardProductMsg> hardProductMsgs =
                Arrays.asList(posMsgs);
        List<PosNameProto.HardProductMsg> tempList = new ArrayList<>();//临时集合
        for (PosNameProto.HardProductMsg hardProductMsg : hardProductMsgs) {
            String typeName = hardProductMsg.typeName;
            //add by zhuangzeqin 2017年9月26日17:34:44 盛代宝 app 硬件类型 要改一下逻辑 只显示盛钱包开头的硬件类型
            if(!TextUtils.isEmpty(typeName) && typeName.startsWith("盛钱包")) {
                tempList.add(hardProductMsg);//把中和付的添加到临时集合里
            }
        }
        for (int i = 0; i < tempList.size(); i++) {
            CustomChooseView chooseView = new CustomChooseView(mContext);
            PosNameProto.HardProductMsg hardProductMsg = tempList.get(i);
            // add by zhuangzeqin 2017年9月26日17:34:44 盛代宝 app 硬件类型；只显示盛钱包开头的选项
            chooseView.setTitle(hardProductMsg.typeName);
            chooseView.setTypeId(hardProductMsg.hpId);
            chooseView.setTag(i);
            chooseView.setOnClickListener(this);
            layout_content.addView(chooseView);
        }
//        for(int i = 0; i < posMsgs.length; i ++){
//            CustomChooseView chooseView = new CustomChooseView(mContext);
//            chooseView.setTitle(posMsgs[i].typeName);
//            chooseView.setTypeId(posMsgs[i].hpId);
//            chooseView.setTag(i);
//            chooseView.setOnClickListener(this);
//            layout_content.addView(chooseView);
//        }

    }

    @Override
    protected void eventOnClick() {
        rl_all.setOnClickListener(this);

        titleBar.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                getsSelectByTypeForResult();
            }
        });
    }

    /**
     * 获取选中的接口；并返回
     */
    private void getsSelectByTypeForResult() {
        intent = new Intent();
        if (isSingle) {
            for (int i = 0; i < layout_content.getChildCount(); i++) {
                CustomChooseView cv = (CustomChooseView) layout_content.getChildAt(i);
                if (cv.getIsSelected()) {
                    intent.putExtra("device_type", cv.getLeftTitle());
                    intent.putExtra("hp_id", cv.getTypeId());
                }
            }
        } else {
            if (isAll) {
                intent.putExtra("isAll", isAll);
            } else {
                StringBuffer buffer = new StringBuffer();
                for (int i = 0; i < layout_content.getChildCount(); i++) {
                    CustomChooseView cv = (CustomChooseView) layout_content.getChildAt(i);
                    if (cv.getIsSelected()) {
                        buffer.append(cv.getLeftTitle() + ",");
                        posIdStr.append(posMsgs[i].hpId + ",");//所选择硬件类型的ID
                    }
                }
                if (buffer.length() > 1) {
                    intent.putExtra("device_type", buffer.substring(0, buffer.length() - 1));
                }
                if (posIdStr.length() > 1) {
                    intent.putExtra("device_ids", posIdStr.substring(0, posIdStr.length() - 1));
                }
            }
        }
        setResult(RESULT_OK, intent);
        finish();
    }


    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        new GrpcTask().execute(Constant.URL.URL, Constant.URL.PORT);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_all://全选
                changeState();
                break;
            default:
                if(v.getTag() != null){
                    int index = (int) v.getTag();
                    singleSelect(index);
                }
                //add by zhuangzeqin 2017年4月21日14:00:53 修改为选择好了之后； 直接返回；无需确定返回
                getsSelectByTypeForResult();
                break;
        }
    }

    /**
     * 单选
     * @param index
     */
    private void singleSelect(int index){
        if(isSingle){
            for (int i = 0; i < layout_content.getChildCount(); i++){
                CustomChooseView childView = (CustomChooseView) layout_content.getChildAt(i);
                if(i == index){
                    childView.setIsSelected(true);
                }else{
                    childView.setIsSelected(false);
                }
            }
        }

    }

    /**
     * 选中全部的时候改变其他状态为不选中
     */
    private void changeState(){
        isAll = !isAll;
        if(isAll){
            iv_all.setVisibility(View.VISIBLE);
            for (int i = 0; i < layout_content.getChildCount(); i++){
                CustomChooseView childView = (CustomChooseView) layout_content.getChildAt(i);
                childView.setIsSelected(false);
                childView.setCanChoose(false);
            }
        }else{
            iv_all.setVisibility(View.GONE);
            for (int i = 0; i < layout_content.getChildCount(); i++){
                CustomChooseView childView = (CustomChooseView) layout_content.getChildAt(i);
                childView.setCanChoose(true);
            }
        }

    }

    private class GrpcTask extends BaseGrpcTask<PosNameProto.HardProductResponse>{

        @Override
        protected PosNameProto.HardProductResponse doInBack(ManagedChannel channel) {
            PosNameApiServiceGrpc.PosNameApiServiceBlockingStub stub = PosNameApiServiceGrpc.newBlockingStub(channel);
            PosNameProto.HardProductRequest request = new PosNameProto.HardProductRequest();
            PosNameProto.HardProductResponse response = stub.getHardProduct(request);
            return response;
        }

        @Override
        protected void updateUI(PosNameProto.HardProductResponse result) {
            dismissProgressDialog();
            if(result == null){
                showToast("查询失败");
                return;
            }
            if("false".equals(result.posStatus.status)){
                showToast("查询失败" + result.posStatus.msg);
                return;
            }
            posMsgs = result.hardProductMsg;
            initData();
        }
    }
}
